from easygui import *
from time import gmtime, strftime
import sys
import cPAMIE as PAMIE
import cReport
import os, sys

# Initialize our stuff.

pathName = os.path.dirname(sys.argv[0])
fullPathName = '%s\\'%os.path.abspath(pathName)

rep = cReport.Report()
rep.initialize()
ie = PAMIE.PAMIE()
ie.showDebugging = True
rep.status ("Starting...!")

# global variables
USR = None
PAS = None
TO = None
MSG = None
sumUSR = str(USR)
sumMSG= str(MSG)
sumTO= str(TO)
currentTime = strftime("%H:%M:%S, %a, %d %b %Y", gmtime())
reportMe = "\n\n\n\n\nReport bugs and any vodafone.ie changes to darren.mcentee@gmail.com"
remainingSMS = None


#-----------------------------------
# Simple intro Message box function.
#

def msgboxOpen(message="Please make sure there is an internet connection available!", title="VODApp", buttonMessage="Continue"):
	rep.status ("*** DEBUG: in msgBox()")
	choices = [buttonMessage]
	reply = buttonbox(message, title, choices)
	return reply

#-----------------------------------
# Simple Info Message box function: a summary of data entered and used by vodafone.
#

def msgboxSummary(message="Summary details", title="VODApp", text=[]):
	global sumUSR, sumMSG, sumTO, currentTime, reportMe
	sumUSR = str(USR)
	sumMSG= str(MSG)
	sumTO= str(TO)
	currentTime
	
	text=["A summary of the details you sent...\n\n",
		  "\t\n Message sent at: ", currentTime,
		  "\t\n From: \t",sumUSR,
		  "\t\n To: \t", sumTO,
		  "\t\n SMS: \t", sumMSG,
		  "\n\n Logging off...",
		  "\n\nYou have successfully logged out!\nwww.vodafone.ie\n\n", reportMe]

	"""
	The text parameter should be a string, or a list or tuple of lines to be
	displayed in the textbox.
	"""
	textbox(message, title, text, codebox=1 )


#-----------------------------------
# The User & Pass GUI function.
#

def UserPassGUI():  #define our vodafone sign in Function
	rep.status("*** DEBUG: in UserPassGUI()")
	try:
#		while 1:
			msg = "VODApp will logon to www.vodafone.ie with your account details and attempt to send an SMS via your web account. Please fill in all fields!"
			title = "VODApp"
			
			fieldNames = ["User Name (#)","Password"]
			fieldValues = []  # we start with blanks for the values
			fieldValues = multpasswordbox(msg,title, fieldNames)
			
			# make sure that none of the fields was left blank
			while 1:
			    if fieldValues == None: break
			    errmsg = ""
			    for i in range(len(fieldNames)):
				    if fieldValues[i].strip() == "":
					    errmsg = errmsg + ('"%s" is a required field.\n' % fieldNames[i])
			    if errmsg == "": break # no problems found
			    fieldValues = multpasswordbox(errmsg, title, fieldNames, fieldValues)
		

			global USR, PAS 
			USR = fieldValues[0]
			PAS = fieldValues[1]
			print "\t *** User:", USR
#			print "\t *** Pass:", PAS

	except:
		print 'GUI USER&PASS: QUIT!'



#-----------------------------------
# The MSG GUI function.
#

def MsgGUI():  #define our vodafone sign in Function
	rep.status("*** DEBUG: in MsgGUI()")
	try:
#		while 1:
			msg = "Enter SMS data.\n"
			title = "VODApp"
			msglimit =160
			fieldNames = ["Recipient","SMS Message"]
			fieldValues = []  # we start with blanks for the values
			fieldValues = multenterbox(msg,title, fieldNames)
			
			# make sure that none of the fields was left blank
			while 1:
			    if fieldValues == None: break
			    errmsg = ""
			    for i in range(len(fieldNames)):
				    if fieldValues[i].strip() == "":
					    errmsg = errmsg + ('"%s" is a required field.\n' % fieldNames[i])
			    if errmsg == "": break # no problems found
			    fieldValues = multenterbox(errmsg, title, fieldNames, fieldValues)

			global TO, MSG 
			TO = fieldValues[0]
			MSG = fieldValues[1]

			print "\t *** Recipient:", TO
			print "\t *** Message  :", MSG
	
	except:
		print 'GUI MSG: QUIT!'



#-----------------------------------
# The signIn function Class.
#

def signIn():  #define our vodafone sign in Function
	rep.status("*** DEBUG: in signIn()")
	rep.status ("Signing In with details...")
	try:

#		print "\t *** User:", USR
#		print "\t *** Pass:", PAS			
#		ie.navigate("www.vodafone.ie/services/messaging/webtext/index.jsp")
		ie.navigate(fullPathName + 'x.htm')
		rep.status ("opened: x.htm.")	
#		rep.status ("URL Opened.")
#		rep.status ("Entered User and Pass...")

#		rep.verify ("username", ie.textBoxSet("username", USR), True)
#		rep.verify ("password", ie.textBoxSet("password", PAS), True)
		
#		myElement = ie.elementFind("input", "alt", "Submit")
#		ie.elementClick(myElement)
#		rep.status ("Login: OK!")

		
		try:
#			ie.linkClick ("Web texts:")
#			rep.status ("Selected 'Web texts' URL.")

#			myElement = ie.elementFind("TEXTAREA", "name", "A46e58445103414217")
#			ie.elementClick(myElement)  			# selects the textbox...
#			rep.status ("Found and selected SMS AREA.")
				
			# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
			# myForm = ie.formName = C2831302	# N.B vodafone forms may have dynamic names, if so get the form name eachtime and store.
			# myForm = formsGetValue (attribute, [filter])
			# myRemaingSMS = ie.formName = None("TEXT", "Messages Remaining")
			# rep.status (myRemaingSMS)
			# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
			
		
			
			# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ENTER YOUR DATA HERE~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
			#	<SCRIPT language=JavaScript>
			#	<!-- document.writeln("<input type='text' class='txtBox2' name='num' size='5' value='160' onfocus='this.form.A46e58445103414217.focus()' ONCHANGE='upperMe2(this.form)'>");-->
			#	</SCRIPT>


			# --------------------------------
			rep.status ("Retreiving SMS counter value...")
			remainingSMS = ie.elementFindByIndex("b", 0)	# <-- finds the first <b> (BOLD) element on page. 
			remainingSMS = int(a.innerText)			# Our smscounter is the next element. (index of 0 i.e. first element)
			rep.status ("Got remaining SMS counter value.")	# This may break if the webpage is changed in the slightest.

			print "\t *************************"
			print "\t Remaining SMS #:", remainingSMS
			print "\t *************************"
			# --------------------------------                                        





			# Sets the text of [ID] box
#			ie.textAreaSet("A46e58445103414217", MSG)	# <---- SMS Message placed into box id: 'A46e58445103414217'
#			rep.status ("Entered SMS-Message.")

#			myElement = ie.elementFind("input", "name", "a0f05090a010004021")
#			ie.elementClick(myElement)  			# selects the nuberbox...
#			rep.status ("Found and selected Number AREA.")
#			ie.textBoxSet("a0f05090a010004021", TO)	# <---- recipient # placed into box id: 'a0f05090a010004021'
#			rep.status ("Entered recipient's number.")
			
#			myElement = ie.elementFind("input", "alt", "Send Now")
#			rep.status ("Found and selected Send button.")

#			ie.elementClick(myElement)
#			rep.status ("SMS Sent !")
#			rep.status ("Message was:")
#			rep.status (MSG)

			# logging off each time.
#			ie.navigate("https://www.vodafone.ie/myv/services/logout/Logout.shtml")	# <--- going to Logout.shtml will automatically call the logout.jsp script.
#			rep.status ("Hit Logoff Button...")
#			rep.status ("You have successfully logged out. \nThank you for using the My Vodafone service!")

			
		except:
			print 'Error Retreiving SMS value!'
			
	except:
		print 'FAILED!'




#-----------------------------------
# The MAIN() function.
#

if __name__ == '__main__':
	msgboxOpen()		# call the opening box
	UserPassGUI()	# call the UserPassGUI
	MsgGUI()		# call the startGUI function
	signIn() 		# call the signIn function
	msgboxSummary()	# call the msgboxSummary function: a summary of data entered and used by vodafone.

